import React, { useState, useEffect } from 'react';
import { Row, Col, Button, Form, DatePicker, message, Tooltip, Alert } from 'antd';
import FormItem from '../../../../components/FormItem';
import services from '../../../../services/api';
import { APIUrl } from '../../../../services/createServices';
import useAppProductEventData from 'src/hook/useAppProductEventData';
import List from './list';
import moment from 'moment';
moment.locale('zh-cn');
const { RangePicker } = DatePicker;

function Step1(props) {
  const [selectRowKeys, setSelectRowKeys] = useState(props.selectRowKeys);
  const [pageParams, setPageParams] = useState(
    props.pageParams || {
      current_page: 1,
      page_size: 10,
    }
  );
  const params = props.params;
  const [list, setList] = useState([]);
  const [totalCount, setTotalCount] = useState(0);
  const [maxNum, setMaxNum] = useState(0);

  const onChangePagination = (pageNumber, type) => {
    setPageParams((pageParams) => {
      return {
        ...pageParams,
        [type]: pageNumber,
      };
    });
  };

  useEffect(() => {
    freshQueryList();
  }, [pageParams.current_page]);

  const getFormParams = () => {
    let params = props.form.getFieldsValue(['data_time', 'app_id', 'product_id', 'event_id']);
    if (!params.event_id) {
      return null;
    }
    if (!params.data_time || params.data_time.length === 0) {
      message.warn('请选择时间');
      return null;
    }
    if (!params.app_id) {
      message.warn('请选择渠道');
      return null;
    }
    params.between_start_data_time = moment(params.data_time[0]).format('YYYY-MM-DD');
    params.between_end_data_time = moment(params.data_time[1]).format('YYYY-MM-DD');
    delete params.data_time;
    return params;
  };

  const freshQueryList = async () => {
    let params = getFormParams();
    if (!params) return;
    let allParams = {
      ...pageParams,
      ...params,
    };
    services.eventMonitor.getDownload(allParams).then((res) => {
      if (res.code === 0) {
        setList(res.data.list);
        setTotalCount(res.data.totalCount);
        setMaxNum(res.data.maxNum);
      } else {
        message.error(res.msg);
      }
    });
  };

  const getColumns = () => {
    return [
      {
        title: '日期',
        key: 'data_time',
        dataIndex: 'data_time',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      {
        title: '渠道',
        key: 'app_name',
        dataIndex: 'app_name',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      {
        title: '产品',
        key: 'product_name',
        dataIndex: 'product_name',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      {
        title: '事件',
        key: 'event_name',
        dataIndex: 'event_name',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      {
        title: '文件名',
        key: 'file_name',
        dataIndex: 'file_name',
        render: (text, record) => {
          return (
            <Tooltip title={text} placement='topLeft'>
              {text}
            </Tooltip>
          );
        },
        ellipsis: true,
      },
      // {
      //   title: '文件大小',
      //   key: 'file_size',
      //   dataIndex: 'file_size',
      //   render: (text, record) => {
      //     return (
      //       <Tooltip title={text + 'MB'} placement='topLeft'>
      //         {text + 'MB'}
      //       </Tooltip>
      //     );
      //   },
      //   ellipsis: true,
      // },
    ];
  };

  const { items } = useAppProductEventData({
    ...props,
    app_id: params.app_id,
    product_id: params.product_id,
    event_id: params.event_id,
    hideLabel: true,
    form: props.form,
    onEventChange: () => {
      setPageParams(
        props.pageParams || {
          current_page: 1,
          page_size: 10,
        }
      );
      setSelectRowKeys([]);
      freshQueryList();
    },
    onAppChange: () => {
      clearList();
    },
    onProductChange: () => {
      clearList();
    },
    app_placeholder: '请选择渠道',
    product_placeholder: '请选择产品',
    event_placeholder: '请选择事件',
  });

  function handleSubmit(e) {
    e.preventDefault();
    if (selectRowKeys.length === 0) return message.warn('请选择下载文件');
    selectRowKeys.forEach((id) => {
      let url = getParamsUrl(`${APIUrl}/event-monitor/bulk-download`, { ids: id });
      let a = document.createElement('a'); // 创建a标签
      a.href = url; // 设置下载地址
      a.download = ''; // 设置下载文件名
      a.click();
      a.remove();
    });
    props.goToNext(selectRowKeys.length, getFormParams(), selectRowKeys, pageParams);
  }

  // 处理get 参数
  function getParamsUrl(url, params) {
    if (Object.keys(params).length !== 0) {
      let str = '';
      for (const key in params) {
        str = str !== '' ? `${str}&${key}=${params[key]}` : `${key}=${params[key]}`;
      }
      return `${url}?${str}`;
    } else {
      return url;
    }
  }
  const formItems1 = [
    {
      label: {
        label: '请求时间',
        className: 'tantuer-form-item2 tantuer-form-item-nowrap',
      },
      name: 'data_time',
      options: {
        initialValue: params.between_start_data_time
          ? [moment(params.between_start_data_time), moment(params.between_end_data_time)]
          : [moment().subtract('days', 6), moment()],
        rules: [{ required: true, message: '请选择时间' }],
      },
      component: (
        <RangePicker
          format='YYYY-MM-DD'
          placeholder={['开始时间', '结束时间']}
          style={{ width: '60%' }}
          disabledDate={(current) => current > moment() || current < moment().subtract('days', 30)}
          onChange={() => {
            setPageParams(
              props.pageParams || {
                current_page: 1,
                page_size: 10,
              }
            );
            setSelectRowKeys([]);
            window.setTimeout(freshQueryList, 0);
          }}
        />
      ),
    },
  ];

  const formItems2 = items;

  // 字段选择配置
  const rowSelection = {
    columnWidth: 30,
    onChange: (selectedRowKeys) => {
      if (selectedRowKeys.length > maxNum) return message.warn(`最多选择${maxNum}个文件同时下载`);
      setSelectRowKeys(selectedRowKeys);
    },
    selectedRowKeys: selectRowKeys,
  };

  const clearList = () => {
    setPageParams(
      props.pageParams || {
        current_page: 1,
        page_size: 10,
      }
    );
    setList([]);
    setSelectRowKeys([]);
  };

  return (
    <div className='tantuer'>
      <div className='tantuer-form'>
        <Form className='login-form'>
          <div className='event-download-content'>
            <div style={{ width: '60%', margin: '20px auto 0 auto' }}>
              <Row type='flex'>
                {formItems1.map((item) => {
                  return (
                    <Col span={24} key={item.name}>
                      <FormItem form={props.form} item={item} colNum={1} />
                    </Col>
                  );
                })}
              </Row>
              <Row type='flex' className='tantuer-form-item2 tantuer-form-item-nowrap'>
                <Col className='ant-form-item-label'>
                  <label className='ant-form-item-required'>基本选项</label>
                </Col>
                <Col span={18} className='flex-1'>
                  <Row type='flex' gutter={10}>
                    {formItems2.map((item) => {
                      return (
                        <Col span={8} key={item.name}>
                          <FormItem form={props.form} item={item} colNum={2} />
                        </Col>
                      );
                    })}
                  </Row>
                </Col>
              </Row>
            </div>
          </div>
        </Form>

        <div style={{ padding: '0 20px' }}>
          {selectRowKeys && selectRowKeys.length > 0 && (
            <Alert
              message={
                <>
                  已选择{selectRowKeys.length}条数据
                  <Button
                    type='link'
                    style={{ marginLeft: '20px' }}
                    onClick={() => {
                      setSelectRowKeys([]);
                    }}
                  >
                    清空
                  </Button>
                </>
              }
              type='success'
              style={{ marginTop: '10px' }}
            />
          )}
          <List
            list={list}
            totalCount={totalCount}
            currentPage={pageParams.current_page}
            pageSize={pageParams.page_size}
            rowSelection={rowSelection}
            onChangePagination={onChangePagination.bind(this)}
            columns={getColumns()}
            queryList={freshQueryList}
            rowKey='coslog_id'
          />
        </div>

        <div className='event-download-ft'>
          <Row type='flex' justify='center'>
            <Col span={12} style={{ textAlign: 'center' }}>
              <Button type='primary' onClick={handleSubmit.bind(this)}>
                下一步
              </Button>
            </Col>
          </Row>
        </div>
      </div>
    </div>
  );
}

export default Form.create()(Step1);
